<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入要发表的内容(最多120字)" maxlength="120" v-model="msg"></textarea>
    <mt-button size="large" type="primary" @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(value,index) in commentsList" :key="value.add_time">
        <div
          class="cmt-title"
        >第{{ index+1 }}楼 &nbsp;用户: {{value.user_name}} &nbsp;&nbsp;发表时间:{{ value.add_time | dataFormate }}</div>
        <div
          class="cmt-body"
        >{{ value.content==='undefined'||value.content==''?'此用户什么也没说':value.content }}</div>
      </div>
    </div>
    <mt-button size="large" type="danger" plain @click="getMore">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from "mint-ui";

export default {
  data() {
    return {
      pageIndex: 1,
      commentsList: [],
      msg: ""
    };
  },
  props: ["id"],
  created() {
    this.getComment();
  },
  methods: {
    getComment() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then(res => {
          console.log(res);
          if (res.body.status == 0) {
            // 为了之前加载的数据不被覆盖,所以,用拼接数组的办法
            this.commentsList = this.commentsList.concat(res.body.message);
          }
        });
    },
    getMore() {
      this.pageIndex++;
      this.getComment();
    },
    postComment() {
      if (this.msg.trim().length == 0) {
        Toast("输入内容为空");
        return;
      }
      this.$http
        .post("api/postcomment/" + this.id, { content: this.msg })
        .then(res => {
          if (res.body.status == 0) {
            this.commentsList.unshift({
              user_name: "匿名用户",
              add_time: new Date(),
              content: this.msg
            });
            this.msg = "";
          }
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }
  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>

